package com.tssup.fesco.init;

import com.tssup.fesco.common.cache.Cache;
import com.tssup.fesco.common.cache.redis.RedisKeyConstants;
import com.tssup.fesco.common.exeception.CacheException;
import com.tssup.fesco.common.exeception.ParameterException;
import com.tssup.fesco.common.exeception.RetException;
import com.tssup.fesco.sales.rule.persistent.mapper.RStaticDataMapper;
import com.tssup.fesco.sales.rule.persistent.pojo.RStaticData;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 缓存数据-全部RStaticData
 * @author haomin
 * @date 2017/6/20
 */
@JobHander(value="CacheStaticDataJob")
@Service
public class CacheStaticDataJob extends IJobHandler{

    @Autowired
    private Cache cache;

    @Autowired
    private RStaticDataMapper rStaticDataMapper;

    @Override
    public ReturnT<String> execute(String... strings) throws Exception {
        XxlJobLogger.log("缓存数据-全部RStaticData");
        try {
            List<RStaticData> rStaticDatas = rStaticDataMapper.selectAll();
            rStaticDatas.stream().forEach(rStaticData -> {
                if (rStaticData != null && rStaticData.getStaticId() != null) {
                    try {
                        cache.set(RedisKeyConstants.getOdcRStaticDataKey(rStaticData.getStaticCode(),rStaticData.getStaticKey(),rStaticData.getParentKey()), rStaticData);
                        XxlJobLogger.log("缓存数据RStaticData:"+rStaticData.getStaticCode()+"/"+rStaticData.getStaticKey());
                    } catch ( CacheException e ) {
                        XxlJobLogger.log("缓存静态数据失败，code:"+rStaticData.getStaticCode()+"，key:"+rStaticData.getStaticKey());
                    }
                }
            });
        }catch (RetException re){
            return new ReturnT<>(Integer.parseInt(re.getRetCode()), re.getResMsg());
        } catch (ParameterException pe) {
            return new ReturnT<>(Integer.parseInt(pe.getCode()), pe.getMessage());
        } catch (Exception e){
            return new ReturnT<>(500,e.getMessage());
        }
        return ReturnT.SUCCESS;
    }
}
